#!/usr/local/bin/python
# -*- coding: gbk -*-
#============================================================
# PDPD.PY                      -- by Dr. ZhuoQing 2020-11-22
#
# Note:
#============================================================

from head import *


if len(sys.argv) < 2:
    tspinsii("import paddle")
    tspinsii("import paddle.fluid as fluid")
    tspinsii("import paddle.fluid.dygraph as dygraph")
    tspinsii("from paddle.fluid.dygraph import Linear\r\n")
    exit()

#------------------------------------------------------------
if sys.argv[1] == 'lr':             # Linear regression
    tspinsii("import paddle")
    tspinsii("import paddle.fluid as fluid")
    tspinsii("import paddle.fluid.dygraph as dygraph")
    tspinsii("from paddle.fluid.dygraph import Linear\r\n")


    tspinsii("#------------------------------------------------------------")
    tspinsii("class Regressor(fluid.dygraph.Layer):")
    tspinsii("    def __init__(self, name_scope):")
    tspinsii("        super(Regressor, self).__init__(name_scope)")
    tspinsii("        self.fc = Linear(input_dim = 1, output_dim = 1, act =None)\r\n")
    tspinsii("    def forward(self, inputs):")
    tspinsii("        x = self.fc(inputs)")
    tspinsii("        return x\r\n\r\n")
    tspinsii("with fluid.dygraph.guard():")
    tspinsii("    model = Regressor('Regressor')")
    tspinsii("    model.train()  #.eval()")
    tspinsii("    opt = fluid.optimizer.SGD(learning_rate=0.05, parameter_list=model.parameters())\r\n\r\n")
    tspinsii("with dygraph.guard(fluid.CPUPlace()):")
    tspinsii("    EPOCH_NUM = 50")
    tspinsii("    BATCH_SIZE = 10\r\n\r\n")
    tspinsii("    for epoch_id in range(EPOCH_NUM):")
    tspinsii("        random.shuffle(train_data)\r\n")
    tspinsii("        mini_batches = [train_data[k:k+BATCH_SIZE] for k in range(0, len(train_data), BATCH_SIZE)]\r\n")
    tspinsii("        for iter_id, mini_batch in enumerate(mini_batches):")
    tspinsii("            x = mini_batch[:, :-1].astype('float32')")
    tspinsii("            y = mini_batch[:, -1:].astype('float32')\r\n")
    tspinsii("            input_data = dygraph.to_variable(x)")
    tspinsii("            target_data = dygraph.to_variable(y)")
    tspinsii("            predicts = model(input_data)")
    tspinsii("            loss = fluid.layers.square_error_cost(predicts, label=target_data)")
    tspinsii("            avg_loss = fluid.layers.mean(loss)\r\n")
    tspinsii("            avg_loss.backward()")
    tspinsii("            opt.minimize(avg_loss)")
    tspinsii("            model.clear_gradients()\r\n")
    tspinsii("        printf('epcoh:{}, loss is:{}'.format(epoch_id, avg_loss.numpy()))\r\n\r\n")
    tspinsii("    fluid.save_dygraph(model.state_dict(), 'LR_model')\r\n")


    exit()





#------------------------------------------------------------
#        END OF FILE : PDPD.PY
#============================================================
